package com.zmj.sy.mom.srv.aps.feign;

import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.LogApi;
import com.zmj.sy.mom.srv.aps.bean.entity.third.PudaProductionLine;
import com.zmj.sy.mom.srv.aps.mapper.PudaProductionLineMapper;
import com.zmj.sy.mom.srv.aps.utils.JsonUtils;
import com.zmj.sy.mom.srv.aps.utils.LogApiUtils;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
@Component
public class PudaApiClient {

    private final LogApiUtils logApiUtils;

    private final PudaProductionLineMapper pudaProductionLineMapper;

    @Value("${project.feign.puda-url}")
    private String pudaUrl;


    /**
     * 发送套料图
     */
    private String sendSteelPlateUrl = "/services/messer/v1/autoProcessingSteelPlate.do";

    private final ObjectMapper objectMapper;


    /**
     * 钢板送达
     *
     * @param productionLine 分拣线编码
     * @param stationCode    上料位编码
     * @param plateCode      钢板号
     * @param nestCode       套料图号
     */
    public void sendPlateEnd(String productionLine, String stationCode, String plateCode, String nestCode) {
//        Boolean isMultiLine = true;//开启多条分拣线
        LogApi logApi = logApiUtils.getSendLog("普达分捡", "钢板送达", "/services/messer/v1/steelIsLoaded.do");
        try {
            if (!StringUtils.hasText(productionLine)) {
                throw SyExceptionUtils.e("分拣线代码不能为空！");
            }

            String hostname = getHostName(productionLine);
            if (!StringUtils.hasText(hostname)) {
                throw SyExceptionUtils.e("未能找到分拣线“" + productionLine + "”对应的普达接口地址，请先维护分拣线对应的普达接口地址");
            }
            String url = hostname + "/services/messer/v1/steelIsLoaded.do";
            Map<String, Object> data = new HashMap<>();
            data.put("production_line", productionLine);
            data.put("station_no", stationCode);
            data.put("mission_no", plateCode);
            data.put("casing_no", nestCode.replace(".cld", ""));
            data.put("casing_model", nestCode.replace(".cld", ""));
            Map<String, Object> bodyMap = new HashMap<>();
            String request_code = UUID.randomUUID().toString();
            String request_name = "PalletReady";
            String request_time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            bodyMap.put("request_code", request_code);
            bodyMap.put("request_name", request_name);
            bodyMap.put("request_time", request_time);
            bodyMap.put("request_data", data);
            String bodyString = JsonUtils.toJsonString(bodyMap);
            log.info(bodyString);
            logApiUtils.setReqStr(logApi, bodyString);
            String post = HttpUtil.post(url, bodyString);
            JsonNode result = objectMapper.readTree(post);

            if (result == null || (result.has("response_result") && !result.get("response_result").asText().equals("0"))) {
                logApiUtils.errorAndSave(logApi, result, result.get("response_result").asText());
                throw SyExceptionUtils.e("普达返回错误:" + post);
            }

            logApiUtils.successAndSave(logApi, result);

        } catch (Exception e) {
            logApiUtils.errorAndSave(logApi, null, e.getMessage());
        }

    }


    /**
     * 获取分拣线对应的服务器接口地址
     *
     * @param productionLine
     * @return
     */
    private String getHostName(String productionLine) {

        PudaProductionLine line = pudaProductionLineMapper.lambdaQuery().eq(PudaProductionLine::getProductionLine, productionLine).one();
        if(line == null || StringUtils.isEmpty(line.getSvrHost())){
            throw SyExceptionUtils.e("未能找到分拣线“" + productionLine + "”对应的普达接口地址，请先维护分拣线对应的普达接口地址");
        }
        return line.getSvrHost();
    }

    /**
     * 发送套料结果
     * @param groupCode
     * @param plateCode
     * @param thickness
     * @param plateDxfUrl
     * @param plmId
     * @param quantity
     */
    public void sendNestResult(String groupCode,
                               String plateCode, BigDecimal thickness, String plateDxfUrl,
                               String nestId, String quantity) {
        Map<String, Object> sendMap1 = new HashMap<>();
        Map<String, Object> sendMap2 = new HashMap<>();
        //1-3_SC_ZDFJ_02
/*        sendMap2.put("production_line", "1-3_SC_ZDFJ_02");
        sendMap2.put("mission_no", plateCode);
        sendMap2.put("thickness", thickness);
        sendMap2.put("casing_no", nestId.replace(".cld", ""));
        sendMap2.put("casing_model", nestId.replace(".cld", ""));
        sendMap2.put("casing_url", plateDxfUrl);
        sendMap2.put("quantity", quantity);
        sendNestix(sendMap2,"http://172.31.5.157");*/
       String plmId= nestId.replace(".cld", "");
       if(groupCode.equals("1-2_JGQG_00")){
            //1-2_SC_ZDFJ_01
            sendMap1.put("production_line", "1-2_SC_ZDFJ_01");
            sendMap1.put("mission_no", plateCode);
            sendMap1.put("thickness", thickness);
            sendMap1.put("casing_no", plmId);
            sendMap1.put("casing_model", plmId);
            sendMap1.put("casing_url", plateDxfUrl);
            sendMap1.put("quantity", quantity);
            sendNestix(sendMap1,"http://172.31.5.135");
            //1-2_SC_ZDFJ_02
            sendMap2.put("production_line", "1-2_SC_ZDFJ_02");
            sendMap2.put("mission_no", plateCode);
            sendMap2.put("thickness", thickness);
            sendMap2.put("casing_no", plmId);
            sendMap2.put("casing_model", plmId);
            sendMap2.put("casing_url", plateDxfUrl);
            sendMap2.put("quantity", quantity);
            sendNestix(sendMap2,"http://172.31.5.135");
        } else if (groupCode.equals("1-3_JGQG_00")) {
            //1-3_SC_ZDFJ_01
            sendMap1.put("production_line", "1-3_SC_ZDFJ_01");
            sendMap1.put("mission_no", plateCode);
            sendMap1.put("thickness", thickness);
            sendMap1.put("casing_no", plmId);
            sendMap1.put("casing_model", plmId);
            sendMap1.put("casing_url", plateDxfUrl);
            sendMap1.put("quantity", quantity);
            sendNestix(sendMap1,"http://172.31.5.156");
            //1-3_SC_ZDFJ_02
            sendMap2.put("production_line", "1-3_SC_ZDFJ_02");
            sendMap2.put("mission_no", plateCode);
            sendMap2.put("thickness", thickness);
            sendMap2.put("casing_no", plmId);
            sendMap2.put("casing_model", plmId);
            sendMap2.put("casing_url", plateDxfUrl);
            sendMap2.put("quantity", quantity);
            sendNestix(sendMap2,"http://172.31.5.157");
        }
    }

    private void sendNestix(Map<String, Object> map,String pudaUrl) {
        Boolean isMultiLine = true;//开启多条分拣线
        LogApi logApi = logApiUtils.getSendLog("普达分捡", "套料图推送", pudaUrl + sendSteelPlateUrl);

        try {
//            String hostname = pudaUrl;
//            if (isMultiLine) {
//                if (StringUtils.isBlank(productionLine)) {
//                    throw new Exception("分拣线代码不能为空！");
//                }
//                hostname = getHostName(productionLine);
//                if (StringUtils.isBlank(hostname)) {
//                    throw new Exception("未能找到分拣线“" + productionLine + "”对应的普达接口地址，请先维护分拣线对应的普达接口地址");
//                }
//            }

            String url = pudaUrl + sendSteelPlateUrl;
            Map<String, Object> bodyMap = new HashMap<>();
            String request_code = UUID.randomUUID().toString();
            String request_name = "PalletReady";
            String request_time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            bodyMap.put("request_code", request_code);
            bodyMap.put("request_name", request_name);
            bodyMap.put("request_time", request_time);
            bodyMap.put("request_data", map);
            String bodyString = JsonUtils.toJsonString(bodyMap);
            log.info(bodyString);
            logApiUtils.setReqStr(logApi, bodyString);
            log.info("普达推送请求内容："+bodyString);
            String post = HttpUtil.post(url, bodyString);
            JsonNode result = objectMapper.readTree(post);
            log.info("普达推送结果："+post);
           /* if (result == null || (result.has("response_result") && !result.get("response_result").asText().equals("0"))) {

                logApiUtils.errorAndSave(logApi, result, result.get("response_data").asText());
            } else {
               logApiUtils.successAndSave(logApi, result);
            }*/
        } catch (Exception e) {
           // logApiUtils.errorAndSave(logApi, null, e.getMessage());
        }
    }
}
